#接口获取城市的天气
import sys
import requests
sys.path.append('../model')
import task_model
import city_model
import weather_model
import time
import datetime

def index():
    #全局事件参数
    cur_time = int(time.time()) #实时时间
    today_end_time = int(time.mktime(time.strptime(str(datetime.date.today()), '%Y-%m-%d')))

    url = 'https://free-api.heweather.com/v5/weather'
    params = {
        'city':'',
        'key':'404e41429361461f8fc0b37d04b06a52'
    }
    #查询城市信息
    t_model = task_model.TaskModel()
    start_data=t_model.get_city_weather()
    if(today_end_time>start_data['update_time']):
        t_model.save_city_weather(0,today_end_time)
        id=0
    else:
        id=start_data['sign']
    #查询一个城市
    c_model = city_model.CityModel()
    city_data=c_model.get_city_by_id(int(id))
    if len(city_data)==0:#如果今天的所有数据已经跑完就退出程序
        exit()
    #获取城市的天气并处理
    try:
        w_model=weather_model.WeatherModel()
        for hf_id in city_data:
            params['city']=hf_id['hf_id']
            re = requests.get(url, params).json()
            daily_forecast = re['HeWeather5'][0]['daily_forecast']
            weather_data={
                'c_id':hf_id['id'],
                'wind':daily_forecast[1]['wind']['sc'],
                'cond':int(daily_forecast[1]['cond']['code_d']),
                'tmp':int(daily_forecast[1]['tmp']['max']),
                'tmp_max':int(daily_forecast[1]['tmp']['max']),
                'tmp_min':int(daily_forecast[1]['tmp']['min']),
                'create_time':today_end_time
            }
            res=w_model.add_city_weather(weather_data)
            #修改任务表标记
            t_model.save_city_weather(hf_id['id'],cur_time)
            if(res==False):
                exit()
            print(weather_data)
    except:
        print('获取天气数据失败:1')
        exit()

    #写入表
if __name__ == '__main__':
    index()